<template>
  <BasicDialog ref="basicDialog" :isVisible="isAlert" width="50%" :title="DialogTitle" @handleSure="handleSure" :isShowSure="flag != 'user_look'">
    <template #content>
      <el-form ref="formRef" :model="formInfo" :rules="flag != 'user_look' ? rules : {}" label-width="120px">
        <el-form-item label="姓名：" prop="uname">
          <el-input type="text" v-model.trim="formInfo.uname" maxlength="20" placeholder="请输入姓名"
            :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="登录名：" prop="loginName">
          <el-input type="text" v-model.trim="formInfo.loginName" maxlength="18" placeholder="请输入登录名"
            :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select v-model="formInfo.sex" placeholder="请选择性别" style="width: 100%" :disabled="isDisabled">
            <el-option v-for="op in sexOptions" :key="op.value" :value="op.value" :label="op.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" prop="roleIds">
          <el-select style="width: 100%" v-model="formInfo.roleIds" multiple value-key="id" :disabled="isDisabled"
            placeholder="请选择角色">
            <el-option v-for="item in roleData" :key="item.id" :label="item.rname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构：" prop="deptName">
          <el-tree-select
            v-model="formInfo.deptid"
            value-key="id"
            :props="{label:'dname'}"
            :check-strictly="true"
            :data="treeData"
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="手机号：" prop="tel">
          <el-input type="text" v-model.trim="formInfo.tel" maxlength="11" placeholder="请输入手机号码"
            :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input type="text" v-model.trim="formInfo.email" maxlength="64" placeholder="请输入邮箱"
            :disabled="isDisabled" />
        </el-form-item>
      </el-form>
    </template>
  </BasicDialog>
</template>
<script lang="ts" setup>
import { FormInfo } from "@components/common/BasicForm/BasicFormTypes";
import type { FormInstance, FormRules } from "element-plus";

import {
  userAdd,
  userEdit,
  getUserById,
} from "@/request/apis/system/user";
import { getRoleTree } from "@/request/apis/system/role";
import { DictTypeEnum, getDictDataList } from "@/utils/dict"

const props = defineProps({
  info: {
    type: Object,
    default: () => {
      return {};
    },
  },
  flag: {
    type: String,
    default: "",
  },
  isAlert: {
    type: Boolean,
    default: false,
  },
  parentData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isDisabled: {
    type: Boolean,
    defalut: false,
  },
  treeData:{
    require:true,
  }
});

const $emits = defineEmits(["closeDialog"]);


// 表单校验规则
const rules = reactive<FormRules>({
  uname: [{ required: true, message: "不能为空", trigger: "blur" }],
  logiName: [
    { required: true, message: "不能为空", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]{6,18}$/, message: "登录名格式不正确，数字，字母，下划线组成6~18位", trigger: "blur" }
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  roleIds: [
    {
      type: "array",
      required: true,
      message: "请至少选择一个角色",
      trigger: "blur",
    },
  ],
  tel: [
    { required: true, message: "不能为空", trigger: "blur" },
    { pattern: /^1[23456789]\d{9}$/, message: "手机号不正确", trigger: "blur" }
  ],
  email: [
    { required: true, message: "不能为空", trigger: "blur" },
    { pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/, message: "邮箱格式不正确", trigger: "blur" }
  ],
})


// 获取角色列表
let roleData = ref([]);

// 获取角色下拉属性
function getRoleData() {
  getRoleTree().then(res => {
    roleData.value = res;
  }).catch(err => {
  })
}

//用户性别列表
const sexOptions = ref([])
function getSexOptions(){
  sexOptions.value = getDictDataList(DictTypeEnum.性别);
}

// 提交表单校验
const formRef = ref<FormInstance>();
const basicDialog = ref();
async function handleSure() {
  formRef.value.validate((valid) => {
    if (valid) {
      basicDialog.value.changeLoading(true);
      let params = {
        ...formInfo.value,
      }
      if (props.flag === "user_add") {
        userAdd(params).then((res: Response) => {
          ElMessage.success("操作成功")
          $emits("closeDialog", 1);
          basicDialog.value.changeLoading(false);
        }).catch(err => {
          basicDialog.value.changeLoading(false);
        })
      } else {
        userEdit(params).then((res: Response) => {
          ElMessage.success("操作成功")
          $emits("closeDialog", 1);
          basicDialog.value.changeLoading(false);
        }).catch(err => {
          basicDialog.value.changeLoading(false);
        })
      }

    }
  });
}

//表单数据
let formInfo = ref<FormInfo>({});
let DialogTitle = ref("查看");
onMounted(() => {
  getRoleData();
  getSexOptions();
  if (props.flag === "user_add") {
    DialogTitle.value = "新增";
    formInfo.value.deptid = props.parentData.id
  } else if (props.flag === "user_edit") {
    DialogTitle.value = "修改"
  }

  if (props.flag !== 'user_add') {
    getUserById(props.info.id).then((res: any) => {
      formInfo.value = res;
    })
  }
});
</script>

<style scoped lang="scss"></style>
